import { useEffect, useState, useRef, useMemo } from 'react';
import { GlobalMargin } from '@/config/style-global';
import { ApostropheStyle } from '@/assets/style/global';
import { debounce } from 'lodash-es';
import DictTag from '../DictTag';
import type { AnyObject } from 'antd/es/_util/type';
import type { Reference } from 'rc-table';
import type { MainTableProps } from './type';

/**
 * 合并renders中与columns中key相等的元素
 */
export function useMergeRenders(
	props: MainTableProps,
	pageInfo: { pageNo: number; pageSize: number }
) {
	const { columns, search, renders, index: tableIndex = { show: true, type: 'increase' } } = props;

	if (!columns?.length) return undefined;

	const copyColumns = [...columns].filter((item) => item);

	const enumColumns = search.filter((item) => item.enum);
	// 查找search配置中有枚举值的配置，在列配置中生成自定义render
	for (const item of enumColumns) {
		if (item.enum?.length) {
			copyColumns.forEach((column) => {
				if (column.key === item.name) {
					column.render = (value) => <DictTag options={item.enum} value={value} />;
				}
			});
		}
	}

	// 检查是否设置最大宽度
	for (const column of copyColumns) {
		if (column.maxWidth) {
			// column.width = column.maxWidth;
			column.render = (value) => (
				<ApostropheStyle width={column.maxWidth} rows={column.clamp}>
					{value}
				</ApostropheStyle>
			);
		}
		column.onHeaderCell = () => ({ style: { whiteSpace: 'nowrap', minWidth: '100px' } });
		column.onCell = () => ({ style: { whiteSpace: 'nowrap', minWidth: '100px' } });
	}

	// 是否插入'序号'列
	if (tableIndex.show && copyColumns.length) {
		copyColumns.unshift({
			title: '序号',
			key: 'index',
			dataIndex: 'index',
			width: props.size === 'small' ? 50 : 70,
			align: 'center',
			fixed: 'left',
			render: (_v, _r, index) => {
				// 有分页时根据页码计算序号，没有则正常排序
				if (pageInfo && tableIndex.type === 'increase') {
					if (!pageInfo.pageSize) {
						console.log('%c [pagination]缺少[pageSize]属性', 'color: red');
					} else if (!pageInfo.pageNo) {
						console.log('%c [pagination]缺少[current]属性', 'color: red');
					}
					return (pageInfo.pageNo - 1) * (pageInfo.pageSize ?? 0) + index + 1;
				} else {
					return index + 1;
				}
			},
			onCell: () => ({ style: { width: '50px' } })
		});
	}

	// 合并对应key的自定义render函数
	for (const renderKey in renders) {
		copyColumns.forEach((column) => {
			// column.align = 'center';
			if (column.key === renderKey) {
				column.render = renders[renderKey];
			}
		});
	}

	return copyColumns;
}

// 自适应高度
export function useScrollHeight(
	props: MainTableProps,
	tableData: { list: any[]; total: number },
	tableHeight: number,
	scrollContentHeight: number
) {
	const tableRef = useRef<Reference>();
	const pageRef = useRef<HTMLDivElement>();

	const [scrollHeight, setScrollHeight] = useState(0);
	const [showScroll, setShowScroll] = useState(false);

	const showScrollFn = () => {
		const mainHeight = window.innerHeight || document.body.clientHeight;
		const tableTbody = tableRef.current.nativeElement.getElementsByClassName('ant-table-tbody')[0];
		const tableThead = tableRef.current.nativeElement.getElementsByClassName('ant-table-thead')[0];
		const topDistance = tableThead?.getBoundingClientRect().bottom ?? 0;
		const pageTop = pageRef.current?.getBoundingClientRect().top ?? 0;
		const result = Math.floor(
			mainHeight - topDistance - (pageTop ? mainHeight - pageTop : GlobalMargin)
		);
		if (result < tableTbody.clientHeight) {
			setScrollHeight(result);
			setShowScroll(true);
		} else {
			setScrollHeight(0);
			setShowScroll(false);
		}
	};

	const handleShowScroll = debounce(showScrollFn, 200);

	useEffect(() => {
		if (props.pagination !== false) {
			window.addEventListener('resize', handleShowScroll);
		}
		return () => {
			if (props.pagination !== false) {
				window.removeEventListener('resize', handleShowScroll);
			}
		};
	}, []);

	useEffect(() => {
		if (tableData.list.length && !scrollContentHeight) {
			showScrollFn();
		} else if (scrollContentHeight) {
			setShowScroll(true);
			setScrollHeight(scrollContentHeight);
		}
	}, [tableData, tableHeight]);

	return { tableRef, pageRef, scrollHeight, showScroll, showScrollFn };
}

/**
 * toolbar中的按钮，根据table中多选的数据的状态，判断按钮是否置灰（有多个数据符合条件的对象时为置灰状态）
 * @param originList selectedRows
 * @param dictValues 允许使用的字典值
 * @param key 根据row中的某个key来判断，默认为：status
 * @returns [是否置灰, 可使用的那个row对象]
 */
export function useWhetherDisabled<RowType = AnyObject>(
	selectedRows: RowType[],
	dictValues: number[],
	key = 'status'
): [boolean, RowType] {
	const activeRow = useRef<RowType>();
	const disabled = useMemo(() => {
		const filterList = selectedRows.filter((item) => dictValues.includes(item[key]));
		activeRow.current = filterList[0];
		return filterList.length !== 1;
	}, [selectedRows]);
	return [disabled, activeRow.current];
}
